package com.shj.web.util;

import com.alibaba.fastjson.JSON;
import com.shj.model.ResResult;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * @Description TODO 响应工具
 * @Author songhuajian
 * @Date 2020/3/4 20:25
 **/
@Slf4j
public class ResultUtil {

    private ResultUtil(){}

    /**
     * @description 使用response输出json
     * @author songhuajian
     * @date 2020/3/12 23:43
     */
    public static void responseJson(ServletResponse response, ResResult result){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("【JSON输出异常】"+e);
        }finally{
            if(out!=null){
                out.flush();
                out.close();
            }
        }
    }

    /**
     * @description 返回成功示例,没有数据
     * @author songhuajian
     * @date 2020/3/12 23:44
     */
    public static ResResult resultSuccess(){
        ResResult result = new ResResult();
        result.setCode(200);
        result.setMsg("SUCCESS");
        return result;
    }

    /**
     * @description 返回成功示例，有数据
     * @author songhuajian
     * @date 2020/3/12 23:44
     */
    public static ResResult resultSuccess(Object object){
        ResResult result = new ResResult();
        result.setCode(200);
        result.setMsg("SUCCESS");
        result.setData(object);
        return result;
    }

    /**
     * @description 返回失败示例，没有数据
     * @author songhuajian
     * @date 2020/3/12 23:44
     */
    public static ResResult resultError(){
        ResResult result = new ResResult();
        result.setCode(500);
        result.setMsg("ERROR");
        return result;
    }

}
